package com.bridgeintelligent.tag.user.mgmt.web;

import com.bridgeintelligent.tag.constants.ExceptionCodes;
import com.bridgeintelligent.tag.user.mgmt.entity.Result;
import com.bridgeintelligent.tag.user.mgmt.entity.UserCodes;
import com.bridgeintelligent.tag.user.mgmt.exception.RoleException;
import com.bridgeintelligent.tag.user.mgmt.pojo.TagPermission;
import com.bridgeintelligent.tag.user.mgmt.pojo.User;
import com.bridgeintelligent.tag.user.mgmt.service.RoleMgmtService;
import com.bridgeintelligent.tag.user.query.service.RoleQueryService;
import com.bridgeintelligent.tag.webserver.security.TagSecurityHelper;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.type.TypeReference;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

@Api(tags = "角色管理")
@RestController
@RequestMapping("/api/role")
public class RoleMgmtController {

    @Autowired
    private RoleMgmtService roleMgmtService;
    @Autowired
    private RoleQueryService roleQueryService;
    static ObjectMapper jackson = new ObjectMapper();
    
    static {
        jackson.setSerializationInclusion( JsonInclude.Include.NON_NULL );
        jackson.disable( DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES );
    }

    /**
     * 新增角色
     *
     * @param roleName
     * @param roleDsc
     * @param pwoerIds
     * @return
     */
    @ApiOperation("新增角色")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "roleName", value = "角色名称", required = true),
            @ApiImplicitParam(paramType = "query", name = "roleDsc", value = "描述", required = true),
            @ApiImplicitParam(paramType = "query", name = "pwoerIds", value = "权限id,以逗号隔开"),
            @ApiImplicitParam(paramType = "query", name = "tagPermsText", value = "标签权限")
    })
    @PostMapping("/add")
    public Result addUser(String roleName, String roleDsc, String[] pwoerIds, String tagPermsText, HttpServletRequest request) {

        try {
            checkId(request);
            //校验角色名是否超过长度
            if (roleName.length() > 50) {
                throw new RoleException(ExceptionCodes.ROLE_40002);
            }
            //校验角色名是否重复
            boolean success = roleQueryService.checkRoleName(roleName);

            if (success) {
                //新建角色
                List<TagPermission> tagPerms = jackson.readValue(tagPermsText,new TypeReference<List<TagPermission>>() {});
                roleMgmtService.addRole(roleName, roleDsc, pwoerIds, tagPerms);
            } else {
                throw new RoleException(ExceptionCodes.ROLE_40001);
            }

            return new Result(UserCodes.SUCCESS);
        } catch (RoleException e) {
            e.printStackTrace();
            return new Result(e.getCode(), "操作失败");
        }
        catch (Exception e) {
            e.printStackTrace();
            return new Result(UserCodes.FAIL, "操作失败");
        }
    }

    /**
     * 删除角色
     *
     * @param roleId
     * @return
     */
    @ApiOperation("删除角色")
    @DeleteMapping("/delete/{roleId}")
    public Result deleteUser(@PathVariable String roleId,HttpServletRequest request) {
        try {
            checkId(request);
            roleMgmtService.deleteRoleByRoleId(roleId);
            return new Result(UserCodes.SUCCESS);
        }catch (RoleException e){
            return new Result(e.getCode(),"操作失败");
        }
    }

    /**
     * 修改角色信息
     *
     * @param roleId
     * @param roleName
     * @param roleDsc
     * @param pwoerIds
     * @return
     */
    @ApiOperation("修改角色信息")
    @ApiImplicitParams({@ApiImplicitParam(paramType = "query", name = "roleId", value = "角色id", required = true),
            @ApiImplicitParam(paramType = "query", name = "roleName", value = "角色名称", required = true),
            @ApiImplicitParam(paramType = "query", name = "roleDsc", value = "描述", required = true),
            @ApiImplicitParam(paramType = "query", name = "pwoerIds", value = "权限id数组")
    })
    @PostMapping("/update")
    public Result updateUser(String roleId, String roleName, String roleDsc, String[] pwoerIds, String tagPermsText, HttpServletRequest request) {

        try {
            //checkId(request);
            //校验角色名是否超过长度
            if (roleName.length() > 50) {
                throw new RoleException(ExceptionCodes.ROLE_40002);
            }
            //校验用户名是否重复
            boolean success = roleQueryService.checkRoleName(roleName);
            List<TagPermission> tagPerms = jackson.readValue(tagPermsText,new TypeReference<List<TagPermission>>() {});

            if (success) {
                roleMgmtService.updateRole(roleId, roleName, roleDsc, pwoerIds, tagPerms);
            } else {
                //查询用户名是否修改
                String oldRoleName = roleQueryService.findRoleNameById(roleId);
                //原来用户未修改用户名
                if (oldRoleName.equals(roleName)) {
                    //修改用户
                    roleMgmtService.updateRole(roleId, roleName, roleDsc, pwoerIds, tagPerms);
                } else {
                    throw new RoleException(ExceptionCodes.ROLE_40001);
                }
            }
            return new Result(UserCodes.SUCCESS);
        } catch (RoleException e) {
            e.printStackTrace();
            return new Result(e.getCode(), "操作失败");
        }
        catch (Exception e) {
            e.printStackTrace();
            return new Result(UserCodes.FAIL, "操作失败");
        }
    }

    @ApiOperation("角色推送测试")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "roleId", value = "角色ID", required = true),
            @ApiImplicitParam(paramType = "query", name = "roleName", value = "角色名称", required = true),
            @ApiImplicitParam(paramType = "query", name = "roleType", value = "角色类型", required = true),
            @ApiImplicitParam(paramType = "query", name = "remark", value = "描述", required = true)
    })
    @PostMapping("/roleTest")
    public Result roleTest(String roleId,String roleName,String roleType, String remark) {
        boolean flag = roleMgmtService.synchRoleInfo(roleId, roleName, roleType, remark);
        if (flag){
            return new Result(UserCodes.SUCCESS);
        }else{
            return new Result(999, "推送失败");
        }
    }

    public void checkId(HttpServletRequest request){
        String cardId = request.getHeader("identity_flag");
        User user = TagSecurityHelper.currentUser();
        if (StringUtils.isEmpty(cardId) || !cardId.equals(user.getUserId())){
            throw new RoleException(ExceptionCodes.USER_30008);
        }
    }

}